<template>
 <!-- <el-input v-model="formData.parentId"/> -->
 <el-tree-select v-model="selectedCategoryId" :data="categoryData" :render-after-expand="false"
                :default-expand-all="true"  :check-strictly="true" @change="change"/>
            <!-- render-after-expand 是否在第一次展开某个树节点后才渲染其子节点
            check-strictly 在显示复选框的情况下，是否严格的遵循父子不互相关联的做法 -->
</template>
<script setup lang="ts">
import{ref,onMounted,watch}from "vue"
import { categoryApi } from "@/api";

// 定义modelValue 的属性
const props =  defineProps({ 
    modelValue: { type: Number, default:0 },
    rootName:{type:String,default:'一级分类'} })
// 数据流向是单向的，从父到子
// 定义触发器 defineEmits  声明 可以从子到父，提前给父亲声明，等会要用到你的money
const emit = defineEmits(['update:modelValue'])


const selectedCategoryId = ref(0)
const categoryData = ref([])
onMounted(()=>{
    callCategoryApi()
})
watch(()=>props.modelValue,(newVal,oldVal)=>{
    // console.log(newVal);
    selectedCategoryId.value = newVal
    
  })
const change = (val:number)=>{
    emit("update:modelValue",val)
    selectedCategoryId.value = val
}
const callCategoryApi = () => {
    categoryApi.select.call().then((categoryDataRes: any) => {
        // console.log(res);

        categoryDataRes.forEach((item:any) => {
            item.value = item.id
            item.label = item.name
        });
//         {
//             value: '1',
//                 label: 'Level one 1',
//                     children: [
//                         {
//                             value: '1-1',
//                             label: 'Level two 1-1'
//                         }
//                     ]
//         }

        // console.log(res);


        let categoryData2 = categoryDataRes.reduce((duzi:any,currentValue:any)=>{
            currentValue.children = categoryDataRes.filter((item:any)=>item.parentId === currentValue.id)
            if(currentValue.parentId === 0){
                duzi.push(currentValue)
            }
            return duzi
        },[])
        categoryData.value = [{value:0,label:props.rootName}].concat(categoryData2)

        // console.log(categoryData2);
        
        // categoryData.value = categoryData.value.concat(res)

    })
}
</script>